/*
 * FileName：CommonCtrl.java 
 * <p>
 * Copyright (c) 2017-2020 <a href="">hermit(1154808491@qq.com)</a>.
 * <p>
 * Licensed under the GNU General Public License, Version 3 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/gpl-3.0.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package com.koine.admin.sys.ctrl;

import com.koine.common.BaseCtrl;
import com.koine.common.Constants;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.util.WebUtils;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.Random;

/**
 * 公共方法 Controller层
 *
 * @author hermit
 * @date 2017 -07-25 11:22:02
 */
@Controller
@RequestMapping("/common")
public class CommonCtrl extends BaseCtrl {

//     /**
//     * 指定图形验证码图片的宽度
//     */
//     private int  w= 60;
//
//     /**
//     * 指定图形验证码图片的高度
//     */
//     private int h = 35;
    /**
     * 指定图形验证码图片的宽度
     */
    private int w = 115;

    /**
     * 指定图形验证码图片的高度
     */
    private int h = 40;


    /*
     * 图形验证码
     *
     * @param response
     */
    @RequestMapping(value = "getverifycode")
    public void getVerifyCode(HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        /*
         * 得到参数高，宽，都为数字时，则使用设置高宽，否则使用默认值
         */
        String width = request.getParameter("width");
        String height = request.getParameter("height");
        if (StringUtils.isNumeric(width) && StringUtils.isNumeric(height)) {
            w = NumberUtils.toInt(width);
            h = NumberUtils.toInt(height);
        }

        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();

        /*
         * 生成背景
         */
        createBackground(g);

        /*
         * 生成字符
         */
        String verifyCode = createCharacter(g);
        WebUtils.setSessionAttribute(request, Constants.SESSION_VERIFY_CODE, verifyCode);

        g.dispose();
        OutputStream out = response.getOutputStream();
        ImageIO.write(image, "JPEG", out);
        out.close();

    }

    private Color getRandColor(int fc, int bc) {
        int f = fc;
        int b = bc;
        Random random = new Random();
        if (f > 255) {
            f = 255;
        }
        if (b > 255) {
            b = 255;
        }
        return new Color(f + random.nextInt(b - f), f + random.nextInt(b - f), f + random.nextInt(b - f));
    }

    private void createBackground(Graphics g) {
        // 填充背景
        g.setColor(getRandColor(220, 250));
        g.fillRect(0, 0, w, h);
        // 加入干扰线条
        for (int i = 0; i < 8; i++) {
            g.setColor(getRandColor(40, 150));
            Random random = new Random();
            int x = random.nextInt(w);
            int y = random.nextInt(h);
            int x1 = random.nextInt(w);
            int y1 = random.nextInt(h);
            g.drawLine(x, y, x1, y1);
        }
    }

    private String createCharacter(Graphics g) {
        char[] codeSeq =
                {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9'};
        String[] fontTypes = {"Arial", "Arial Black", "AvantGarde Bk BT", "Calibri"};
        Random random = new Random();
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            String r = String.valueOf(codeSeq[random.nextInt(codeSeq.length)]);// random.nextInt(10));
            g.setColor(new Color(50 + random.nextInt(100), 50 + random.nextInt(100), 50 + random.nextInt(100)));
            g.setFont(new  Font("Times New Roman", Font.BOLD, 30));
            g.drawString(r, 17 * i + 20, 29 + random.nextInt(8));
            s.append(r);
        }
        return s.toString();
    }

    /**
     * 系统错误页
     *
     * @return
     */
    @RequestMapping(value = "error")
    public String error() {
        return "redirect:/views/error/404.html";
    }

    /**
     * 跳转首页
     *
     * @return
     */
    @RequestMapping(value = "index")
    public String index() {
        return "redirect:/index";
    }

    /**
     * 跳转登录首页
     *
     * @return
     */
    @RequestMapping(value = "login")
    public String login() {
        return "redirect:/views/index/logreg.html";
    }

    /**
     * 系统权限页面
     *
     * @return
     */
    @RequestMapping(value = "unauth")
    public String unauth() {
        return "redirect:/views/error/unauth.html";
    }

    /**
     * 系统第三方完善资料页面
     *
     * @return
     */
    @RequestMapping(value = "openid")
    public String openid() {
        return "redirect:/views/index/openid.html";
    }

    /**
     * 出现错误时跳转
     *
     * @return
     */
    @RequestMapping(value = "openid/{code}")
    public String openidError(@PathVariable("code") String code) {
        return "redirect:/views/index/openid.html?errorcode=" + code;
    }
}
